<?php defined('SYSPATH') OR die('No direct access allowed.');

// version 0.1

class GoogleAddress_Plugin extends WB_FormItem
{
	var $api_key;
	var $lat = 'lat';
	var $lng = 'lng';
	var $local_def = '';
	var $local_inp = '';	//jquery expression to catch address parts
	
    function __construct($name, $params)
    {
    	parent::__construct($name, $params, 'text googleaddress');
        
        $this->api_key = Kohana::config('gmaps.api_key');
        $this->local_def = empty($this->params['local_def']) ? '' : $this->params['local_def'];
        $this->local_inp = empty($this->params['local_inp']) ? '' : str_replace('_sharp_', '#', $this->params['local_inp']);
    
        $this->lat = isset($this->params['lat']) ? $this->params['lat'] : $this->lat;
        $this->lng = isset($this->params['lng']) ? $this->params['lng'] : $this->lng;
			
		$this->form_columns[$this->lat] = $this->db_table.'.'.$this->lat;
		$this->form_columns[$this->lng] = $this->db_table.'.'.$this->lng;
		$this->db_columns[$this->lat] = $this->db_table.'.'.$this->lat;
		$this->db_columns[$this->lng] = $this->db_table.'.'.$this->lng;
		
		Event::add('wb_controller.pre_render_form', array($this, 'init_form'));
    }

	
	/**
	 * Renders the form element
	 * 
	 * @return string
	 */
	public function render_item()
	{
		$str = $this->prefix;
		$str .= form::label($this->name, $this->label);
		$str .= form::input($this->name, $this->value[$this->name], html::attributes($this->attributes));
		$str .= '<input type="hidden" name="'.$this->lat.'" id="'.$this->lat.'" value="'.$this->value[$this->lat].'" />';
		$str .= '<input type="hidden" name="'.$this->lng.'" id="'.$this->lng.'" value="'.$this->value[$this->lng].'" />';
		$str .= '<span class="resultimg">&nbsp;</span>';
		$str .= '<span class="result"></span>';
		if ($this->description) $str .= '<span class="description">'.$this->description.'</span>';
		$str .= $this->suffix;
		
		return $str;
	}
	
	public function prep_db()
	{
		$this->value[$this->lat] = empty($this->value[$this->lat]) ? NULL : $this->value[$this->lat];
		$this->value[$this->lng] = empty($this->value[$this->lng]) ? NULL : $this->value[$this->lng];
		
		return $this->value;
	}
	
	function init_form()
	{
		Kohana::instance()->wb_template->js('google_api', 'http://www.google.com/jsapi?key='.$this->api_key, FALSE);
		Kohana::instance()->wb_template->js('plugins/googleaddress');
		Kohana::instance()->wb_template->script($this->name.'GoogleAddress', $this->_get_js_template());
	}
    
	function _get_js_template()
	{
		$em = $this->name;
		$template = '
var inp_'.$em.';
var result_'.$em.';
var resultimg_'.$em.';

$(document).ready(function(){
	
	inp_'.$em.' = $("#'.$em.'");
	var parent = inp_'.$em.'.parent();
	inp_'.$em.'.change(function(){
		$(this).data("new", true);
	});
	
	result_'.$em.' = $(".result", parent);
	resultimg_'.$em.' = $(".resultimg", parent);
	lat_'.$em.' = $("#'.$this->lat.'");
	lng_'.$em.' = $("#'.$this->lng.'");
	
	
	function getAddress'.$em.'(e)
	{
		e.stopPropagation();
		
		var inp = inp_'.$em.';
		var result = result_'.$em.';
		var resultimg = resultimg_'.$em.';
		
		var local_def = "'.$this->local_def.'";
		var local_inp = "'.$this->local_inp.'";
		var address = inp_'.$em.'.val();
		
		if (local_inp!="")
		{
			$(local_inp).each(function(){
				var v = $(this).val();
				var html = $(this).html();
				if (html.indexOf("</option>")>0) v = $("option[value="+v+"]", this).text();
				if (v.length>0) address += ", "+v;
			});
		}
		if (local_def!="") address += ", "+local_def;
		
		if (geocoder) {
			geocoder.getLatLng(
				address,
				function(point) {
					if ( ! point) {
						var t = "'.Kohana::lang('googleaddress_plugin.not_found').'";
						t += "<br />\n'.Kohana::lang('googleaddress_plugin.address_sent').' " + address + ".";
						result.html(t);
						lat_'.$em.'.val("");
						lng_'.$em.'.val("");
						resultimg.addClass("truncate").removeClass("tick");
					} else {
						var t = "'.Kohana::lang('googleaddress_plugin.coords').'" + point;
						t += "<br />\nA megadott cím: " + address;
						result.html(t);
						lat_'.$em.'.val(point.lat());
						lng_'.$em.'.val(point.lng());
						resultimg.addClass("tick").removeClass("truncate");
					}
				}
			);
		}
	}
	inp_'.$em.'.blur(getAddress'.$em.');
	resultimg_'.$em.'.click(getAddress'.$em.');
});
		';
		return $template;
	}
}

// End of GoogleAddress_Plugin